package UDPEcho;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

//客户端
//此处的ip使用的是字符串,点分10进制风格
public class UDPEchoClient {
    private DatagramSocket socket = null;
    private String severIp;
    private int severPort;

    public UDPEchoClient(String serverIp,int severPort) throws SocketException {
            this.severIp = serverIp;
            this.severPort = severPort;
        //参数是请求的目的IP和目的端口
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("->");//提示用户输入一些东西
            //要做四个事情
            // 1、从控制台读取要发送请求的数据
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();
            //2、构造请求并发送
            DatagramPacket requestPavket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),request.getBytes().length, InetAddress.getByName(severIp),severPort);
            socket.send(requestPavket);
            //3、读取服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4、把响应打印到控制台上
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
            }

    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient udpEchoClient = new UDPEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}

